<template>
  <div class="page-container">
    <div style="text-align: left;">
      <div class="quickbar">
        <el-button type="warning" icon="el-icon-video-play" size="mini" round>
          <router-link :to="'/deploy/proccess?projectId=' + projectId">
            部署
          </router-link>
        </el-button>
        <el-button type="primary" icon="el-icon-refresh-left" size="mini" round @click="onRollback(projectId)">回滚</el-button>
      </div>
    </div>
    <div class="block-wrapper">
      <div style="display: flex; flex-wrap: wrap;">
        <!-- 副本集合 -->
        <div style="display: inline-block;">
          <div class="replicasets">
            <div class="main" style="padding-left: 20px;">
              <!-- 副本集标题 -->
              <div class="app_block_title_small">
                历史版本:  (当前副本数: {{ replicaSetList.length }} )
              </div>
              <div class="replicasets-wrapper">
                <el-timeline :reverse="reverse" style="padding-left: 5px;padding-top: 5px;">
                  <el-timeline-item
                    v-for="(rs, index) in replicaSetList"
                    :key="index"
                    :type="rs.status"
                  >
                    <div style="font-size: 13px; color: rgb(145, 145, 145); margin-bottom: 8px; padding-top: 2px;">
                      已创建: {{ rs.creationTimestamp }}
                    </div>
                    <span>
                      <span class="el-popover__reference-wrapper">
                        <div
                          class="item replicaset-row el-popover__reference"
                          :class="selectRowClass(rs)"
                          @click="onReplicaSetRowSelect(rs)"
                        >
                          <div class="replicaset selected">
                            <!-- 标题行 -->
                            <div style="line-height: 28px; height: 28px; overflow: hidden;">
                              <div class="nowrap" style="width: calc(100% - 120px); display: inline-block;">
                                {{ rs.name }}
                              </div>
                              <div class="deployment_undo_wrapper" style="margin-right: 6px; float: right; line-height: 28px;">
                                <el-tag :type="rs.status">
                                  #{{ rs.revision }}
                                </el-tag>
                              </div>
                            </div>
                            <!-- 副本数量 -->
                            <div style="font-size: 12px; line-height: 28px;">
                              期望: {{ rs.replicas }} 当前: {{ rs.availableReplicas }} 就绪: {{ rs.readyReplicas }}
                            </div>
                          </div>
                        </div>
                      </span>
                    </span>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧父面板 -->
        <div style="display: flex; flex-wrap: wrap; width: calc(100% - 410px);">

          <!-- pods列表面板 -->
          <div class="pods">
            <div style="min-height: 50px;">

              <!-- 副本集标题 -->
              <div class="app_block_title_small">
                副本集合{{ replicaCurrent }}所管理的容器组
              </div>

              <!-- 副本集下的pod列表 -->
              <div class="pods-wrapper">
                <span>
                  <div
                    v-for="(pod, index) in podList"
                    :key="index"
                    style="overflow: hidden; height: 66px;"
                    @click="onPodRowSelect(pod)"
                  >
                    <!-- pod 基本信息 -->
                    <div
                      class="pod item"
                      :class="selectPodClass(pod)"
                    >

                      <!-- pod状态 -->
                      <div style="float: right; top: -1px; right: -5px; position: relative; z-index: 0;">
                        <el-tag :type="pod.ready ? 'success' : 'warning'">
                          {{ pod.ready ? 'Ready' : 'Not Ready' }}
                        </el-tag>
                      </div>

                      <!-- pod名称 -->
                      <div class="app_text_mono podtitle" :class="{ 'delete-row' : pod.containerStatusesState==='terminated' }">
                        {{ pod.podName }}
                      </div>

                      <!-- pod创建时间+ip -->
                      <div style="line-height: 28px;">
                        <!-- ip -->
                        <div style="display: inline-block; vertical-align: bottom;">
                          <div v-if="pod.podIP" style="display: inline-block; width: 138px;">
                            C:{{ pod.podIP }}
                          </div>
                          H:{{ pod.hostIP ? pod.hostIP : '' }}
                        </div>
                      </div>

                    </div>
                  </div>
                </span>
              </div>
            </div>
          </div>

          <!-- pod详情面板 -->
          <div style="display: inline-block; margin-left: 10px; min-width: 440px; width: calc(100% - 370px); max-width: 100%;">
            <div class="pod-wrapper">
              <div class="podDetails" style="margin-bottom: 20px;">
                <div style="min-height: 50vh;">
                  <span>
                    <el-form v-if="podCurrentObj != null" ref="podCurrentForm" label-position="left" :inline="true" :model="podCurrentObj" size="small" label-width="100px" @submit.native.prevent>
                      <div class="title">
                        <span class="kind">
                          容器组
                        </span>
                        {{ podCurrentObj.podName }}

                        <span class="el-tooltip text item time">
                          {{ podCurrentObj.creationTimestamp }}
                        </span>
                      </div>

                      <div class="info">
                        <!-- ip -->
                        <div class="kvs">
                          <el-form-item label="容器组IP" style="width: 40%">
                            {{ podCurrentObj.podIP ? podCurrentObj.podIP : '' }}
                          </el-form-item>
                          <el-form-item label="状态" style="width: 40%">
                            {{ podCurrentObj.phase }}
                          </el-form-item>
                        </div>

                        <!-- condition -->
                        <div style="display: flex; flex-wrap: wrap; margin-right: -10px;">
                          <div v-if="podCurrentObj.podScheduled" class="condition app_text_mono">
                            <i :class="[podCurrentObj.podScheduled.status ? 'el-icon-success success' : 'el-icon-error error']" />
                            <div class="type" :class="{ 'error': !podCurrentObj.podScheduled.status }">
                              {{ podCurrentObj.podScheduled.status ? '已调度' : '未调度' }}
                            </div>
                            <span class="condition-time">
                              {{ podCurrentObj.podScheduled.lastTransitionTime }}
                            </span>
                            <div v-if="!podCurrentObj.podScheduled.status" class="app_text_description">
                              <span class="app_text_regular">
                                {{ podCurrentObj.podScheduled.reason }}
                              </span>
                              {{ podCurrentObj.podScheduled.message }}
                            </div>
                          </div>
                          <div v-if="podCurrentObj.initialized" class="condition app_text_mono">
                            <i :class="[podCurrentObj.initialized.status ? 'el-icon-success success' : 'el-icon-error error']" />
                            <div class="type" :class="{ 'error': !podCurrentObj.initialized.status }">
                              {{ podCurrentObj.initialized.status ? '已就绪' : '未就绪' }}
                            </div>
                            <span class="condition-time">
                              {{ podCurrentObj.initialized.lastTransitionTime }}
                            </span>
                            <div v-if="!podCurrentObj.initialized.status" class="app_text_description">
                              <span class="app_text_regular">
                                {{ podCurrentObj.initialized.reason }}
                              </span>
                              {{ podCurrentObj.initialized.message }}
                            </div>
                          </div>
                          <div v-if="podCurrentObj.readyCondition" class="condition app_text_mono">
                            <i :class="[podCurrentObj.readyCondition.status ? 'el-icon-success success' : 'el-icon-error error']" />
                            <div class="type" :class="{ 'error': !podCurrentObj.readyCondition.status }">
                              {{ podCurrentObj.readyCondition.status ? '容器已就绪' : '容器未就绪' }}
                            </div>
                            <span class="condition-time">
                              {{ podCurrentObj.readyCondition.lastTransitionTime }}
                            </span>
                            <div v-if="!podCurrentObj.readyCondition.status" class="app_text_description">
                              <span class="app_text_regular">
                                {{ podCurrentObj.readyCondition.reason }}
                              </span>
                              {{ podCurrentObj.readyCondition.message }}
                            </div>
                          </div>
                          <div v-if="podCurrentObj.containersReady" class="condition app_text_mono">
                            <i :class="[podCurrentObj.containersReady.status ? 'el-icon-success success' : 'el-icon-error error']" />
                            <div class="type" :class="{ 'error': !podCurrentObj.containersReady.status }">
                              {{ podCurrentObj.containersReady.status ? '容器组已就绪' : '容器组未就绪' }}
                            </div>
                            <span class="condition-time">
                              {{ podCurrentObj.containersReady.lastTransitionTime }}
                            </span>
                            <div v-if="!podCurrentObj.containersReady.status" class="app_text_description">
                              <span class="app_text_regular">
                                {{ podCurrentObj.containersReady.reason }}
                              </span>
                              {{ podCurrentObj.containersReady.message }}
                            </div>
                          </div>
                        </div>

                        <div style="margin-top: 10px;">
                          <el-card class="container" shadow="false" style="width: 100%;">
                            <div class="icon" style="width: 40px;display: inline-block;vertical-align: top;">
                              <div class="docker" style="width: 40px;height: 40px;">
                                <svg-icon icon-class="app" style="margin-right: 5px" />
                              </div>

                              <router-link :to="'/k8s/podlog?projectId='+projectId+'&podName='+podCurrentObj.podName">
                                <span style="vertical-align: middle; font-size: 12px;cursor: pointer;">日志</span>
                              </router-link>

                            </div>

                            <div class="content">
                              <el-tag type="success" size="mini" effect="dark" color="#234883" style="border-color: #234883">容器</el-tag>

                              <span style="margin-left: 10px;">
                                {{ podCurrentObj.containerName }}
                              </span>

                              <div style="display: inline-block; float: right; margin-right: 10px;">
                                <div v-if="podCpu" style="cursor: pointer;" @click="getPodMetric">
                                  <i class="el-icon-refresh" style="margin-right: 5px;" />

                                  <span class="app_text_label">
                                    CPU
                                  </span>
                                  <span class="app_text_mono">
                                    {{ podCpu }}
                                  </span>
                                  <span class="app_text_label"> m / 内存 </span>
                                  <span class="app_text_mono">
                                    {{ podMem }}
                                  </span>
                                  <span class="app_text_label"> MiB</span>
                                </div>
                              </div>

                              <div class="image">
                                <span class="imageLabel" style="color: #919191;">
                                  镜像：
                                </span>
                                <span class="app_text_mono">
                                  {{ podCurrentObj.image }}
                                </span>
                              </div>

                              <div>
                                <div style="text-align: left; margin-top: 10px; display: flex; flex-wrap: wrap;">
                                  <div class="el-button-group" />

                                  <!-- 端口 -->
                                  <div style="flex-grow: 1; height: 28px;">
                                    <div>
                                      <div class="ports app_text_mono" style="width: calc(100% - 28px);">

                                        <div v-if="podCurrentObj.ports" class="port">
                                          <div
                                            v-for="(port, index) in podCurrentObj.ports"
                                            :key="index"
                                            class="containerPort"
                                          >
                                            {{ port.containerPort + '/' + port.protocol }}
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </el-card>
                        </div>
                      </div>
                    </el-form>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 对话框 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="showDeployListDialog" title="历史部署记录（双击部署）" width="70%">
      <el-table ref="table" v-loading="deployListLoading" :data="deployList" style="width: 100%;" @row-dblclick="deployListClick">
        <el-table-column prop="deployTime" label="部署时间" width="150" />
        <el-table-column prop="buildImageUrl" label="镜像" />
        <el-table-column prop="sourceBranch" label="部署分支" width="180" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>

import { mapGetters } from 'vuex'
import * as APIS from '@/api/server/index'
import global_const from '@/mixins/global_const'

export default {
  name: 'DpServerRunningStatus',
  components: {
  },
  mixins: [global_const],
  props: {
    projectId: {
      type: Number,
      default: () => { return -1 }
    }
  },
  data() {
    return {
      replicaSetLoading: false,
      replicaSetList: [],
      replicaCurrent: null,

      podList: [],
      podLoading: false,
      podCurrent: null,
      podCurrentObj: null,

      podCpu: null,
      podMem: null,

      reverse: false,

      showDeployListDialog: false,
      deployList: [],
      deployListLoading: false
    }
  },
  computed: {
    ...mapGetters([
      'env'
    ]),
    replicasParam() {
      return {
        env: this.env,
        projectId: this.projectId
      }
    },
    replicaSetParam() {
      return {
        env: this.env,
        projectId: this.projectId,
        replicaSetName: this.replicaCurrent
      }
    },
    podParam() {
      return {
        env: this.env,
        projectId: this.projectId,
        podName: this.podCurrent,

        setIntRequest: null
      }
    }
  },
  watch: {},
  created() {
  },
  mounted() {
    this.getReplicaSet()
    this.$bus.$on('global-env-change', data => {
    })
    this.$nextTick(() => {
      this.startTimer()
    })
  },
  beforeDestroy() {
    this.$bus.$off('global-env-change')
    this.stopIntRequest()
  },
  methods: {
    stopIntRequest() {
      this.setIntRequest && clearInterval(this.setIntRequest)
      this.setIntRequest = null // 内存回收
    },
    startTimer() {
      const _this = this
      this.setIntRequest = setInterval(() => {
        _this.getReplicaSet()
      }, 10000)
    },
    getReplicaSet() {
      this.replicaSetLoading = true
      return APIS.getReplicaSet(this.replicasParam).then(data => {
        this.replicaSetList = data
        this.selectDefaultReplicaSet()
      }).finally(() => {
        this.replicaSetLoading = false
      })
    },
    getPodMetric() {
      if (this.podCurrentObj === null) {
        return
      }
      return APIS.getPodMetric(this.podParam).then(data => {
        this.podCpu = data.cpu * 1000
        this.podMem = (data.mem / 1000 / 1000).toFixed(2)
      }).finally(() => {
      })
    },
    selectDefaultReplicaSet() {
      // 默认选择成功的副本集
      const len = this.replicaSetList.length
      for (let i = 0; i < len; i++) {
        const rs = this.replicaSetList[i]
        if (this.replicaCurrent !== null && rs.name === this.replicaCurrent.name) {
          this.onReplicaSetRowSelect(rs)
          return
        } else if (this.replicaCurrent === null && rs.status === 'success') {
          this.onReplicaSetRowSelect(rs)
          return
        }
      }

      // 没有则默认选择第一个
      if (len > 0) {
        this.onReplicaSetRowSelect(this.replicaSetList[0])
      }
    },
    getPods() {
      this.podLoading = true
      return APIS.getPods(this.replicaSetParam).then(data => {
        this.podList = data

        // 默认选择第一个
        if (data.length > 0) {
          this.onPodRowSelect(data[0])
        } else {
          this.onPodRowSelect(null)
        }
      }).finally(() => {
        this.podLoading = false
      })
    },
    onReplicaSetRowSelect(rs) {
      this.replicaCurrent = rs.name

      // 获取pod列表
      this.getPods()
    },
    selectRowClass(rs) {
      const selected = (this.replicaCurrent === rs.name)
      let rowClass = rs.status + '-row-plain'
      if (selected) {
        rowClass = rowClass.replace('-plain', '')
      }
      return rowClass
    },
    selectPodClass(pod) {
      const selected = (this.podCurrent === pod.podName)
      const ready = pod.ready
      let status = ''
      if (ready) {
        status = 'success'
      } else {
        if (pod.phase === 'Running') {
          status = 'completed'
        } else {
          status = 'warning'
        }
      }
      let rowClass = status + '-row-plain'
      if (selected) {
        rowClass = rowClass.replace('-plain', '')
      }
      return rowClass
    },
    onPodRowSelect(pod) {
      this.podCurrentObj = pod
      this.podCurrent = pod === null ? '' : pod.podName

      this.getPodMetric()
    },

    onRollback(projectId) {
      this.showDeployListDialog = true

      this.deployListLoading = true
      APIS.queryDeployRec({
        projectId: projectId,
        env: this.env,
        deployStatus: this.DEPLOY_STATUS_SUCCESS,
        stage: this.STAGE_DEPLOY_CHECK
      }).then(res => {
        const len = res.content.length
        this.deployList = len > 5 ? res.content.slice(0, 5) : res.content
      }).finally(() => {
        this.deployListLoading = false
      })
    },
    deployListClick(row, column, event) {
      // 部署历史版本
      APIS.deployByHistory({
        id: row.id
      }).then(res => {
        this.showDeployListDialog = false

        const deployLogPath = `/deploy/proccess?projectId=${row.projectId}&deployRecId=${res.id}`
        this.$router.push(deployLogPath)
      }).finally(() => {
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

  .quickbar {
    height: 48px;
    background-color: #dfe6ec;
    padding: 10px;
    display: flex;
    line-height: 48px;
  }

  .block-wrapper {
    padding-top: 5px;
    background: white;

    .replicasets {
      width: 382px;
      margin-right: 0px;
      padding: 0 5px 0 0px;
      z-index: 1;

      .item {
        padding: 5px 10px;
        width: 308px;
        outline-style: none;
      }

      .replicaset {
        cursor: pointer;
        padding-left: 6px;
        border-radius: 5px;
        height: 56px;
      }

      .replicaset-row {
        font-family: Monaco,Menlo,Consolas,Bitstream Vera Sans Mono,monospace;
        cursor: pointer;
        transition: background-color .25s ease;
      }
    }

    .replicasets-wrapper {
      width: 362px;
      height: calc(100vh - 305px);
      overflow: hidden;;
    }

    .summary {
      height: 0px;
      display: block;
    }

    .pods {
      display: inline-block;
      width: 358px;
    }

    .pods-wrapper {
      width: 358px;
      max-height: calc(100vh - 305px);
      overflow: hidden;
      overflow-y: auto;
    }

    .pod {
      border: 1px dashed #a7b6cd;
      display: inline-block;
      padding: 6px 10px;
      user-select: none;
      font-size: 12px;
      cursor: pointer;
      line-height: 22px;
      height: 58px;
      width: 350px;
      margin: 0 10px 10px 0;
      transition: .2s;
    }

    .item {
      border-radius: 5px;
    }

    .nowrap {
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }

    .podtitle {
      width: calc(100% - 90px);
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }

    .flag {
      height: 13px;
      width: 12px;
      font-size: 10px;
      background-color: #234883;
      border-radius: 2px;
      text-align: center;
      vertical-align: top;
      line-height: 16px;
      margin-top: 6px;
      margin-right: 1px;

      .host {
        background-color: #909399;
      }
    }

    .wrapper {
      font-weight: 400;
      font-size: 13px;
      height: 28px;
      width: 360px;
      text-align: left;
      overflow: hidden;
      padding: 2px;
    }
  }

  .app_block_title_small {
    padding: 5px 0px;
    font-weight:500;
    font-size: 14px;
  }

  .completed-row {
    background: #909399;
    color: #fff;
  }
  .completed-row-plain {
    background-color: #e9edf3;
    font-family: Monaco,Menlo,Consolas,Bitstream Vera Sans Mono,monospace;
    cursor: pointer;
    transition: background-color .25s ease;
  }
  .success-row-plain {
    background: #cff2e9;
  }
  .success-row {
    background: #0fbe8f;
    color: #fff;
  }
  .warning-row {
    background: #ff8807;
    color: #fff;
  }
  .warning-row-plain {
    background: #ffe7cd;
  }
  .delete-row {
    text-decoration: line-through;
  }

  .title {
    margin-top: 10px;
    padding: 5px 10px;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    font-weight: 600;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    background-color: #234883;
    border: 1px solid #234883;
    color: #fff;
  }

  .kind {
    margin-right: 5px;
  }

  .time {
    font-size: 13px;
    font-weight: 400;
  }

  .podDetails .kvs .pod-details-kv {
    margin-right: 20px;
    display: inline-block;
    -webkit-box-flex: 1;
    flex-grow: 1;
  }

  .info {
    background-color: #f1f4f8;
    padding: 10px;
  }

  :v-deep .el-form-item__label {
    text-align: left !important;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #646464;
    line-height: 40px;
    padding: 0 12px 0 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: solid red 1px;
  }

  .pod-details-kv {
    font-size: 12px;
  }

  .condition {
    display: inline-block;
    font-size: 12px;
    margin-right: 10px;
    padding: 5px 10px;
    background-color: #fff;
    margin-top: 5px;
    border-radius: 5px;
    -webkit-box-flex: 1;
    flex-grow: 1;
  }

  .type {
    display: inline-block;
    width: 150px;
    margin-left: 5px;
    font-weight: 700;
  }

  .error {
    color: #f44656;
  }

  .success {
    color: #0fbe8f;
  }

  .condition-time {
    color: #646464;
    word-break: keep-all;
  }

  .condition-error {
    color: #f44656;
  }

  .app_text_description {
    font-size: 13px;
    color: #909399;
  }

  .app_text_regular {
    font-size: 12px;
    color: #606266;
  }

  .container {
    display: inline-block;
    vertical-align: top;

    .content {
      display: inline-block;
      width: calc(100% - 60px);

      .image {
        font-size: 13px;
        color: #646464;
        padding: 5px 0;
        line-height: 24px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
    }
  }

  ::v-deep .el-card {
    border-radius: 10px;
  }
  :v-deep .el-card__body {
    padding: 10px 20px !important;
  }

  .app_text_label {
    font-size: 12px;
    color: #909399;
  }
  .app_text_mono {
    font-family: Consolas,Menlo,Bitstream Vera Sans Mono,Monaco,微软雅黑,monospace;
  }

  .el-button-group {
    display: inline-block;
    vertical-align: middle;
    width: 100%;
    margin-bottom: 20px;
    text-align: right;

    .el-button--primary {
      border-color: #234883;
      background-color: #234883;
    }
  }

  .ports {
    display: inline-block;
    overflow: hidden;

    font-size: 14px;
    line-height: 28px;
    height: 28px;

    .port {
      margin-right: 10px;
      line-height: 15px;
      border-radius: 10px;
      vertical-align: middle;

      .containerPort {
        display: inline-block;
        color: #fff;
        height: 20px;
        vertical-align: middle;

        background-color: #234883;
        padding: 2px 10px 2px 12px;
        border-radius: 10px;

        margin-right: 10px;
      }

      .protocol {
        display: inline-block;
        color: #fff;
        height: 16px;
        vertical-align: middle;

        margin-right: 10px;
        line-height: 16px;
        background-color: #657fa8;
        padding: 0px 0px;
        border-radius: 0px;
      }
    }
  }
</style>
